package com.aar.rest.util;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

import java.io.StringReader;

public class Parse {

	public static String[][] parse(String xml) {	
		String[][] data = new String[20][4];
		try {
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(new InputSource(new StringReader(xml)));
			doc.getDocumentElement().normalize();
			if(doc.getDocumentElement().getNodeName().equals("enfants")){
				System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
				NodeList nList = doc.getElementsByTagName("enfant");
				System.out.println("-----------------------");
	 
				for (int temp = 0; temp < nList.getLength(); temp++) {			
					Node nNode = nList.item(temp);
					if (nNode.getNodeType() == Node.ELEMENT_NODE) {
						Element eElement = (Element) nNode;	
						data[temp][0] = getTagValue("id", eElement);
						data[temp][1] = getTagValue("nom", eElement);
						data[temp][2] = getTagValue("ville", eElement);
						data[temp][3] = getTagValue("estSage", eElement);
					}
				}
			}else if(doc.getDocumentElement().getNodeName().equals("cadeaux")){
				System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
				NodeList nList = doc.getElementsByTagName("cadeau");
				System.out.println("-----------------------");
	 
				for (int temp = 0; temp < nList.getLength(); temp++) {			
					Node nNode = nList.item(temp);
					if (nNode.getNodeType() == Node.ELEMENT_NODE) {
						Element eElement = (Element) nNode;	
						data[temp][0] = getTagValue("id", eElement);
						data[temp][1] = getTagValue("nom", eElement);
						data[temp][2] = getTagValue("valider", eElement);
						data[temp][3] = getTagValue("fabriquer", eElement);
					}
				}		
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return data;
	}
 
	private static String getTagValue(String sTag, Element eElement) {
		NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
	    Node nValue = (Node) nlList.item(0);
	    return nValue.getNodeValue();
	}
}